package co.fitstart.admin.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;

import co.fitstart.admin.service.AreaService;
import co.fitstart.entity.site.Area;
import co.fitstart.entity.site.Site;

/** 
 * 
 * @author haiyan_xiao
 *
 */
@Service("areaService")
public class AreaServiceImpl implements AreaService {
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.service.AreaService#create(java.lang.String)
     */
    public void create(String name) {
        if(this.load(name) == null) {
            Area area = new Area(name);
            genericDaoSupport.save(area);
        } else {
            throw new BusinessException("已存在的区域名");
        }
    }
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.service.AreaService#edit(java.lang.Long, java.lang.String, java.util.List)
     */
    public void edit(Long areaId, String name, List<Long> siteIds) {
        Area area = genericDaoSupport.load(Area.class, areaId);
        
        if(area != null) {
            genericDaoSupport.update(area.edit(name));
            
            List<Site> sites = area.getSites();
            
            if(sites != null && !sites.isEmpty()) {
                for(Site site : sites) {
                    genericDaoSupport.update(site.editArea(null));
                }
            }
            
            if(siteIds != null && !siteIds.isEmpty()) {
                for(Long siteId : siteIds) {
                    Site site = genericDaoSupport.load(Site.class, siteId);
                    
                    genericDaoSupport.update(site.editArea(area));
                }
            }
        }
    }
    
    /**
     * 
     * @param name
     * @return
     */
    private Area load(String name) {
        return genericDaoSupport.searchForObject("FROM Area WHERE name = :name", "name", name, Area.class);
    }
}
